#!/usr/bin/env python
# encoding: utf-8
"""
service.py

Created by AlanYang on 2011-06-26.
Copyright (c) 2011 __MyCompanyName__. All rights reserved.
"""
import os
import time
import logging
import cPickle
import redis
import pymongo
import config
import searchengine

logging.basicConfig(filename = os.path.join(os.getcwd(), config.LOG_FILE), level = logging.INFO, filemode = 'a+', format = '%(asctime)s - %(levelname)s: %(message)s')  
    
def run():
    logging.info('start search server.')
    cache = redis.Redis(config.REDIS_HOST,config.REDIS_PORT,config.DB_REDIS_SEARCH)
    while True:
        job = cache.rpop(config.JOBS_KEY)
        if job:
            print job
            conn = pymongo.Connection(config.MONGO_HOST,config.MONGO_PORT)
            db = conn.freeasker
            try:
                command = cPickle.loads(job)
                if len(command) == 4:
                    fun , fields , content ,name = command
                    func = searchengine.__dict__.get(fun,None)
                    if func and '_id' in content:
                        sid = func(fields,content)
                        db.search.insert({'_id':content['_id'],'sid':sid,'name':name})
                        logging.info('%s>>%s>>%s>>%s>>%s>>%s'%(fun,content['_id'],sid,fields,str(content),name))
                elif len(command) == 6:
                    fun , docid , opera,fields,content ,name= command
                    func = searchengine.__dict__.get(fun,None)
                    if func:
                        sid = func(docid,opera,fields,content)
                        logging.info('%s>>%s>>%s>>%s>>%s'%(fun,sid,opera,fields,str(content)))
            except Exception, e:
                logging.error(e)
            conn.disconnect()
        time.sleep(1)
        
if __name__ == '__main__':
    run()
    print searchengine.__dict__['index']
#    run()
